package com.zhongke.common.widget

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.util.AttributeSet
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import com.zhongke.common.R
import com.zhongke.common.utils.ZKStatusBarUtil
import com.zhongke.common.widget.TitleView.RightTextStyle
import com.zhongke.common.widget.TitleView.Style
import com.zhongke.common.utils.dp
import com.zhongke.common.utils.gone
import com.zhongke.common.utils.singleClick

/**
 * 标题栏
 *
 * 带有返回按钮，更多按钮和右侧按钮
 *
 * 默认情况下更多按钮和右侧按钮不显示，并且这两个按钮不能同时显示
 *
 * 标题栏默认情况下没有背景颜色，底部不带圆角
 *
 * 可以通过 [setStyle] 来设置标题栏的样式
 * [Style.NORMAL] 是默认样式，就是普通的标题栏
 * [Style.ROUND_CORNER] 底部为圆角的标题栏
 * [Style.NONE] 不显示标题栏
 * 然后可以通过 [setColor] 设置标题栏的颜色
 *
 * 控制更多按钮的显示/隐藏状态可以调用 [showMoreButton] 方法
 * 设置右侧按钮的文字可以通过 [setRightText] 方法
 *
 * 右侧按钮有两种样式，一种为纯文字，另一种为文字加上白色的圆角背景，通过 [setRightTextStyle] 可以设置右侧按钮的样式
 * [RightTextStyle.TEXT_ONLY] 为纯文字样式，[RightTextStyle.TEXT_ROUND_BACKGROUND] 为带有白色圆角背景样式
 *
 * 可以通过 [setRightTextEnabled] 来设置右侧按钮是否可点击，并且已经处理好了不可点击时的文字颜色
 */
class TitleView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

    companion object {
        val DISABLED_TEXT_COLOR = Color.parseColor("#ABAFB3")
        val NORMAL_TEXT_COLOR = Color.parseColor("#333333")
    }

    /**
     * 标题栏样式
     */
    enum class Style {
        /**
         * 底部是圆角的
         */
        ROUND_CORNER,

        /**
         * 底部是平的
         */
        NORMAL,

        /**
         * 不显示标题栏
         */
        NONE
    }

    /**
     * 标题栏右侧按钮样式
     */
    enum class RightTextStyle {
        /**
         * 只显示文字
         */
        TEXT_ONLY,

        /**
         * 带圆角背景
         */
        TEXT_ROUND_BACKGROUND
    }

    private var style = Style.NORMAL
    private var rightTextStyle = RightTextStyle.TEXT_ONLY

    /**
     * 标题栏的颜色
     */
    var color = 0
        private set
    private var rightTextBgColor = Color.WHITE

    private lateinit var layerDrawable: LayerDrawable
    private lateinit var gradientDrawable: GradientDrawable
    private lateinit var colorDrawable: ColorDrawable

    private val btnBack: ImageView
    private val btnMore: ImageView
    private val titleText: TextView
    private val btnRight: TextView

    private var onBackClickListener: OnClickListener? = null
    private var onMoreClickListener: OnClickListener? = null
    private var onRightTextClickListener: OnClickListener? = null

    init {
        LayoutInflater.from(context).inflate(R.layout.title_view, this)
        btnBack = findViewById(R.id.btnBack)
        btnMore = findViewById(R.id.btnMore)
        titleText = findViewById(R.id.title)
        btnRight = findViewById(R.id.btnRight)

        setColor(Color.parseColor("#F4F5FA"))

        btnBack.singleClick {
            onBackClickListener?.onClick(it)
        }
        btnMore.singleClick {
            onMoreClickListener?.onClick(it)
        }
        btnRight.singleClick {
            onRightTextClickListener?.onClick(it)
        }
    }

    fun setTitle(title: String?): TitleView {
        titleText.text = title
        return this
    }

    fun getTitle(): CharSequence = titleText.text

    fun hideBackButton(): TitleView {
        btnBack.gone()
        return this
    }

    fun setBackButtonBackground(res: Int) {
        btnBack.setImageResource(res)
    }

    fun showMoreButton(show: Boolean): TitleView {
        btnMore.isVisible = show
        if (show) {
            btnRight.gone()
        }
        return this
    }

    /**
     * 如果传入空字符串或者 null 则会隐藏右侧按钮
     */
    fun setRightText(text: String?): TitleView {
        btnRight.isVisible = !text.isNullOrEmpty()

        if (btnRight.isVisible) {
            showMoreButton(false)
            btnRight.text = text
        }

        return this
    }

    fun setColor(@ColorInt color: Int): TitleView {
        if (style == Style.NONE) return this

        this.color = color
        setStyle(style)

        return this
    }

    fun setStyle(style: Style): TitleView {
        this.style = style
        when (style) {
            Style.NONE -> gone()
            Style.ROUND_CORNER -> {
                if (!::gradientDrawable.isInitialized) {
                    val corner = 24.dp.toFloat()
                    gradientDrawable = GradientDrawable().apply {
                        cornerRadii = floatArrayOf(0f, 0f, 0f, 0f, corner, corner, corner, corner)
                    }
                    colorDrawable = ColorDrawable(Color.TRANSPARENT)
                    layerDrawable = LayerDrawable(arrayOf(colorDrawable, gradientDrawable))
                }
                gradientDrawable.color = ColorStateList.valueOf(color)
                background = layerDrawable
            }
            Style.NORMAL -> {
                setBackgroundColor(color)
            }
        }
        return this
    }

    /**
     * 当标题栏的样式是底部圆角时[Style.ROUND_CORNER]改变标题栏中圆角以外的颜色
     */
    fun setBottomBackgroundColor(color: Int): TitleView {
        if (style == Style.ROUND_CORNER && ::colorDrawable.isInitialized) {
            colorDrawable.color = color
        }
        return this
    }

    /**
     * @param bgColor 背景颜色，只有当[style]为[RightTextStyle.TEXT_ROUND_BACKGROUND]时才会生效
     */
    fun setRightTextStyle(style: RightTextStyle, @ColorInt bgColor: Int = Color.WHITE): TitleView {
        rightTextStyle = style

        if (style == RightTextStyle.TEXT_ONLY) {
            btnRight.background = null
            btnRight.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16f)
            btnRight.setPadding(0)
        } else {
            rightTextBgColor = bgColor
            btnRight.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12f)
            var bg = btnRight.background
            if (bg == null) {
                bg = GradientDrawable().apply {
                    cornerRadius = 18.dp.toFloat()
                    color = ColorStateList.valueOf(bgColor)
                }
                btnRight.background = bg
            }
            btnRight.setPadding(14.dp, 4.dp, 14.dp, 5.dp)
            if (bgColor != Color.WHITE) {
                btnRight.setTextColor(Color.WHITE)
            }
        }

        return this
    }

    fun setRightTextEnabled(enabled: Boolean): TitleView {
        if (btnRight.isVisible) {
            btnRight.isEnabled = enabled
        }

        if (rightTextStyle == RightTextStyle.TEXT_ROUND_BACKGROUND) {
            val bg = btnRight.background
            if (enabled) {
                bg.setTint(rightTextBgColor)
                btnRight.setTextColor(if (rightTextBgColor != Color.WHITE) Color.WHITE else NORMAL_TEXT_COLOR)
            } else {
                bg.setTint(Color.WHITE)
                btnRight.setTextColor(DISABLED_TEXT_COLOR)
            }
        } else {
            btnRight.setTextColor(
                if (enabled) NORMAL_TEXT_COLOR
                else DISABLED_TEXT_COLOR
            )
        }

        return this
    }

    fun setOnBackClickListener(l: OnClickListener) {
        onBackClickListener = l
    }

    fun setOnMoreClickListener(l: OnClickListener) {
        onMoreClickListener = l
    }

    fun setOnRightTextClickListener(l: OnClickListener) {
        onRightTextClickListener = l
    }

    private var IS_EXACTLY = false
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        var modeHeight = MeasureSpec.getMode(heightMeasureSpec)
        if (modeHeight == MeasureSpec.AT_MOST) {
            setMeasuredDimension(measuredWidth, 44.dp)
        } else {
            IS_EXACTLY = true
            setMeasuredDimension(
                measuredWidth,
                measuredHeight + ZKStatusBarUtil.getStatusBarHeight(context)
            )
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)

        if (IS_EXACTLY) {
            var layoutParams = FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
            )
            layoutParams.gravity = Gravity.BOTTOM
            this.getChildAt(0).layoutParams = layoutParams
        }

    }


}